package com.qishon.pc.domain.Application;

import com.qishon.pc.domain.model.ProgressControl;
import com.qishon.pc.domain.model.ProgressSteps;
import com.qishon.pc.domain.service.ProgressControlService;
import com.qishon.pc.domain.service.ProgressStepsService;
import com.qishon.pc.domain.util.GirardEnum;
import com.qishon.pc.domain.util.KillProcessUtil;
import com.qishon.pc.domain.util.Sender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

/**
 * Created by yuquan.hu on 2016/12/23.
 */
@Slf4j
@Component
public class ProgressControlManager {
    //获取渲染文件路径
    @Value("${run.path}")
    private String filePath;

    @Value("${maya.script.file}")
    private String mayaPath;
    @Value("${render.type}")
    private String renderType;
    @Autowired
    private ProgressStepsService stepsSerivce;
    @Autowired
    private ProgressControlService progressControlService;

    @Autowired
    private KillProcessUtil killProcessUtil;

    @Autowired
    private Sender sender;
    public List<ProgressControl> findByGirard(Map<String,Object> map) {
        map.put("girard","file");
        return progressControlService.findByGirard(map);
    }

    public List<ProgressControl> findUnComplete(Map<String,Object> map) {
        return progressControlService.findUnComplete(map);
    }


    public List<ProgressControl> findComplete(Map<String,Object> map) {
        return progressControlService.findComplete(map);
    }

//    public ProgressControl addProgressControl(ProgressControl progressControl){
//        return progressControlRepository.addProgressControl(progressControl);
//    }
//    public ProgressControl updateProgress(ProgressControl progressControl){
//        return progressControlRepository.updateProgress(progressControl);
//    }
//
//    public ProgressControl updateVersion(ProgressControl progressControl){
//        return progressControlRepository.updateVersion(progressControl);
//    }
//
//    public ProgressControl updateCurNode(ProgressControl progressControl){
//        return progressControlRepository.updateCurNode(progressControl);
//    }
//    public ProgressControl findById(int id){
//        return progressControlRepository.findById(id);
//    }


    /**
     * 开始执行渲染过程
     */
    public void startRendering(){
        //第一、二步：遍历Cloud Render目录,根据firstStep去遍历01.Model，并添加到progress_control表中
       List<ProgressControl> progressControls = progressControlService.addProgressControls(1);
       if (!progressControls.isEmpty()){
            for (int i = 0;i < progressControls.size();i++){
                ProgressControl progressControl = progressControls.get(i);
                //判断这笔记录是新增的记录,progressControl 的proStatus值不等于0，说明是废弃对象
                if (progressControl != null && progressControl.getProStatus() == 0){
                    if( progressControl.getProgress().equals("0%") && progressControl.getCurNode() == 1){
                        //判断该记录是否存在子表记录
                        List<ProgressSteps> stepsList = stepsSerivce.findByGirardId(progressControl);
                        if (stepsList.isEmpty()){
                            //新增所有子表记录
                            for (int step = 1; step < 9;step++){
                                ProgressSteps progressSteps = stepsSerivce.addProCtrlSteps(step,progressControls.get(i));
                            }
                        }
                        // 第三步：调用执行maya脚本，执行成功之后返回结果1；
                        sender.send(2,progressControl.getId(),progressControl.getGirard(),"渲染","renderReceiver");
                        //修改款号当前节点
                        progressControlService.updateProgress(progressControl,14.3+"%");
                        progressControlService.updateCurNode(progressControl,2);
                    }else {
                        //这笔记录是已经存在的,而且不是历史记录,查继续执行后续的任务
                        this.continueRendering(progressControl);
                    }
                }
            }
       }
    }

    /**
     * 根据当前步骤继续执行渲染
     * @param progressControl 当前款号记录
     */
    public void continueRendering(ProgressControl progressControl){
        //获取当前步骤
        String stepName = GirardEnum.findByKey(progressControl.getCurNode()).getFileName();
        ProgressSteps steps = stepsSerivce.findByGirardIdAndStepName(progressControl.getId(),stepName);
        if (steps.getStepNo().toUpperCase().equals("02.RENDER") && renderType.equals("maya")){
            if (!this.closeMayaProcess(progressControl).equals("success")){
                log.info("Because Maya shutdown failure,the Rendering Task could not close");
            }
        }
        if (steps.getAllFiles() == steps.getCompletedFiles()){//当前步骤已完成，执行下一步骤
            int nextNode = progressControl.getCurNode()+1;
            //判断是否是最后一步，不是的话继续执行下一步，是的话修改Progress Control当前完成度
            if (!steps.getStepNo().toUpperCase().equals("08.DONE")){
                int countAllFiles = stepsSerivce.countAllFiles(progressControl.getId());
                int countCompletedFiles = stepsSerivce.countCompletedFilesFiles(progressControl.getId());
                float countPress = (countCompletedFiles*100.0f/(countAllFiles*1.0f));
                DecimalFormat df = new DecimalFormat("0.00");
                String _countPress = df.format(countPress);
                log.info(_countPress);
                progressControlService.updateProgress(progressControl,_countPress+"%");
                progressControlService.updateCurNode(progressControl,nextNode);
                String sendType = GirardEnum.findByKey(nextNode).getSendCode();
                String taskName = GirardEnum.findByKey(nextNode).getFileName();
                sender.send(progressControl.getCurNode(),progressControl.getId(),progressControl.getGirard(),taskName,sendType);
            }else {
                progressControlService.updateProgress(progressControl,"100%");
                int version = progressControlService.countVersion()+1;
                progressControlService.updateVersion(progressControl,version);
                stepsSerivce.clearFiles(filePath+"\\"+"01.Model"+"\\"+progressControl.getGirard());
            }
        }else{//更新已完成的文件
            int compressFiles = stepsSerivce.getCompressFiles(steps);
            steps.setCompletedFiles(compressFiles);
            log.info("GirardId:"+steps.getGirardId() + ";AllFiles:" + steps.getAllFiles()  + ";CompletedFiles:" +  steps.getCompletedFiles());
            stepsSerivce.updateCompletedFiles(steps);
        }
    }


    /**
     * 关闭maya程序
     * @param progressControl
     */
    public String closeMayaProcess(ProgressControl progressControl){
        String fileName = progressControl.getGirard()+".txt";
        String result = "error";
        try {
            File file = new File(filePath+"\\"+"01.Model"+"\\"+progressControl.getGirard()+"\\"+fileName);
            if (file.exists()){
                String closeResult = killProcessUtil.killProcess("maya.exe");
                if (closeResult.equals("success")){
                    log.info("closing maya.exe success");
                    result = "success";
                }else {
                    log.info("closing maya.exe failed");
                }
            }else {
                log.info("Rendering has not over");
            }
            return result;
        }catch (Exception e){
            log.info(fileName+" is defined");
        }
        return result;
    }
}
